package cn.zysheep.singleton.demo7;

import cn.zysheep.pattern.singleton.demo2.Singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @ClassName: Client
 * @Description: 破坏单例模式   序列化和反射
 * @Author: lyw
 * @Date: 2022/10/17 22:09
 */
public class Client {
    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Client.writerObjToFile();
        Client.readObjToFile();
        Client.readObjToFile();
        Client.reflect();
    }
    /**
     * 序列化破坏单例
     */
    public static void writerObjToFile()  {
        Singleton instance = Singleton.getInstance();
        String path = "a.txt";
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(instance);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void readObjToFile()  {
        String path = "a.txt";
        try {
            FileInputStream fileInputStream = new FileInputStream(path);
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Singleton singleton = (Singleton)objectInputStream.readObject();
            System.out.println(singleton);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反射破坏单例
     */
    public static void reflect() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<cn.zysheep.pattern.singleton.demo5.Singleton> singletonClass =
                cn.zysheep.pattern.singleton.demo5.Singleton.class;
        Constructor<cn.zysheep.pattern.singleton.demo5.Singleton> declaredConstructor = singletonClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        cn.zysheep.pattern.singleton.demo5.Singleton singleton = declaredConstructor.newInstance();
        cn.zysheep.pattern.singleton.demo5.Singleton singleton1 = declaredConstructor.newInstance();
        System.out.println(singleton == singleton1);
    }
}
